package Inet;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    //Socket 用于创建套接字
    //还需要创建两个变量用于存储 服务器的IP地址和端口号 知道发送目标
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    //创建构造方法 实例化对象  传入服务器IP地址和端口号
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    private void start() throws IOException {
        System.out.println("客户端启动！");
        //输入要传输的数据
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要发送的请求->");
            //1、从控制台读取用户输入
            String request = scanner.next();
            //2、构造请求并发送
            //发送请求时，得有数据，有目标
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                                                                 InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //3、读取响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4、显示响应到控制台
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
